using CameraManager.Models;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Threading.Tasks;

namespace CameraManager.Models;

public class CameraManager
{
    public ObservableCollection<CameraDevice> Cameras { get; } = new();
    private readonly List<CameraDevice> _activeCameras = new();

    public async Task InitializeAsync()
    {
        await StopAllCamerasAsync();
        Cameras.Clear();
        // 检测可用的摄像头
        var availableCameras = await DetectAvailableCamerasAsync();
        
        foreach (var index in availableCameras)
        {
            Cameras.Add(new CameraDevice(index));
        }
    }

    private async Task<List<int>> DetectAvailableCamerasAsync()
    {
        return await Task.Run(() =>
        {
            var availableCameras = new List<int>();
            
            // 尝试检测最多10个摄像头
            for (int i = 0; i < 10; i++)
            {
                using var capture = new OpenCvSharp.VideoCapture(i);
                if (capture.IsOpened())
                {
                    availableCameras.Add(i);
                    capture.Release();
                }
            }
            
            return availableCameras;
        });
    }

    public async Task StartCameraAsync(CameraDevice camera)
    {
        if (!_activeCameras.Contains(camera))
        {
            await camera.StartAsync();
            _activeCameras.Add(camera);
        }
    }

    public async Task StopCameraAsync(CameraDevice camera)
    {
        if (_activeCameras.Contains(camera))
        {
            await camera.StopAsync();
            _activeCameras.Remove(camera);
        }
    }

    public async Task StopAllCamerasAsync()
    {
        var tasks = _activeCameras.Select(camera => camera.StopAsync()).ToArray();
        await Task.WhenAll(tasks);
        _activeCameras.Clear();
    }
}
